import struct
class ESOutputPacket():
	def __init__(self, cmd):
		self.length = 0
		self.buffer = ''
		self.cmd = cmd

	def begin(self, cmd):
		self.cmd = cmd;

	def writeByte(self, data):
		self.length += 1
		self.buffer += struct.pack('!b', data);

	def writeShort(self, data):
		self.length += 2
		self.buffer += struct.pack('!h', data);

	def writeInt(self, data):
		self.length += 4
		self.buffer += struct.pack('!i', data);

	def writeInt64(self, data):
		self.length += 8
		self.buffer += struct.pack('!q', data);

	def writeString(self, data):
		l = len(data)
		self.length += l+1+4
		self.buffer += struct.pack('!i', l+1);
		format = '!'+str(l)+'s1x'
		self.buffer += struct.pack(format, data);

	def end(self):
		str = self.buffer;
		self.buffer = struct.pack('!2chhh', 'E', 'S', self.cmd, 1, self.length)
		self.buffer += str;

	def printx(self):
		print("espacket print : %s" % self.buffer);

	def bufferx(self):
		return self.buffer


class ESInputPacket():

	def __init__(self, packet):
		self.buffer = packet
		self.length = 0
		self.nowLen = self.length
		self.cmd = 0
		e, s, self.cmd, ver, self.length= struct.unpack('!2chhh', self.buffer[0:8] );
		self.buffer = self.buffer[8:]

	def getPacketCmd(self):
		return self.cmd

	def getPacketLength(self):
		return self.length

	def readByte(self):
		self.nowLen -= 1;	
		data, = struct.unpack('!b', self.buffer[0:1] );
		self.buffer = self.buffer[1:]
		return data 

	def readShort(self):
		self.nowLen -= 2;	
		data, = struct.unpack('!h', self.buffer[0:2] );
		self.buffer = self.buffer[2:]
		return data 
		
	def readInt(self):
		self.nowLen -= 4;	
		data, = struct.unpack('!i', self.buffer[0:4] );
		self.buffer = self.buffer[4:]
		return data 

	def readInt64(self):
		self.nowLen -= 8;	
		data, = struct.unpack('!q', self.buffer[0:8] );
		self.buffer = self.buffer[8:]
		return data 

	def readString(self):
		length, = struct.unpack('!i', self.buffer[0:4] );
		format = '!'+str(length)+'s'
		data, = struct.unpack(format, self.buffer[4:length+4] );
		self.buffer = self.buffer[4+length:]
		return data 
	
	def printx(self):
		pass;


